<template>
  <div class="leader-audit">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>团长审核</span>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="searchForm.phone" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="自提点名称">
            <el-input v-model="searchForm.storeName" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="searchForm.address" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="自提点类型">
            <el-select v-model="searchForm.storeType" style="width: 180px" placeholder="全部">
              <el-option
                v-for="item in storeTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="button-group">
          <el-button type="primary" @click="handleSearch">检索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="danger" @click="handleBatchApprove">批量通过</el-button>
          <el-button type="warning" @click="handleBatchReject">批量作废</el-button>
        </div>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" class="demo-tabs">
        <el-tab-pane label="待审核" name="pending" />
        <el-tab-pane label="已通过" name="approved" />
        <el-tab-pane label="已作废" name="rejected" />
      </el-tabs>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="申请ID" width="120" />
        <el-table-column prop="applyTime" label="申请时间" width="160" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="storeName" label="自提点名称" width="150" />
        <el-table-column prop="address" label="自提点地址" min-width="200" />
        <el-table-column prop="storeType" label="自提点类型" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-button type="success" link @click="handleApprove(scope.row)">通过</el-button>
            <el-button type="danger" link @click="handleReject(scope.row)">作废</el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty 
            description="当前条件下暂无数据" 
            :image-size="100"
          />
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[2, 5, 10, 20]"
          :layout="'prev, pager, next, ->, sizes'"
          :total="total"
          :pager-count="5"
          background
          prev-text="«"
          next-text="»"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
        <div class="pagination-info">
          当前条件共检索到 <span style="color:#f00">{{ total }}</span> 条相关信息
        </div>
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog v-model="dialogVisible" title="查看申请" width="900px" :close-on-click-modal="false">
      <div v-if="currentRow">
        <!-- 申请信息 -->
        <h4>申请信息</h4>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="申请ID">{{ currentRow.id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="授权微信信息">{{ currentRow.wxInfo || '-' }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ currentRow.applyTime || '-' }}</el-descriptions-item>
        </el-descriptions>
        <!-- 自提点位置 -->
        <h4 style="margin-top:16px;">自提点位置</h4>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="是否有门店">{{ currentRow.hasStore ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item label="自提点名称">{{ currentRow.storeName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="自提点地址">{{ currentRow.address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="坐标">{{ currentRow.coordinate || '-' }}</el-descriptions-item>
          <el-descriptions-item label="门牌号">{{ currentRow.doorNumber || '-' }}</el-descriptions-item>
        </el-descriptions>
        <!-- 自提点信息 -->
        <h4 style="margin-top:16px;">自提点信息</h4>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="自提点类型">{{ currentRow.storeType || '-' }}</el-descriptions-item>
          <el-descriptions-item label="开始营业时间">{{ currentRow.openTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="结束营业时间">{{ currentRow.closeTime || '-' }}</el-descriptions-item>
        </el-descriptions>
        <el-row style="margin-top:12px;">
          <el-col :span="8">
            <div>营业执照：</div>
            <el-image v-if="currentRow.licenseImg" :src="currentRow.licenseImg" style="width:120px;height:120px;" fit="contain" />
            <div v-else style="width:120px;height:120px;background:#fafbfc;border:1px solid #eee;"></div>
          </el-col>
          <el-col :span="8">
            <div>自提点照片：</div>
            <el-image v-if="currentRow.storeImg" :src="currentRow.storeImg" style="width:120px;height:120px;" fit="contain" />
            <div v-else style="width:120px;height:120px;background:#fafbfc;border:1px solid #eee;"></div>
          </el-col>
        </el-row>
        <!-- 团长信息 -->
        <h4 style="margin-top:16px;">团长信息</h4>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="团长姓名">{{ currentRow.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ currentRow.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备用号码">{{ currentRow.backupPhone || '-' }}</el-descriptions-item>
        </el-descriptions>
        <div style="margin-top:12px;">身份证信息：</div>
        <el-row>
          <el-col :span="6">
            <el-image v-if="currentRow.idCardFront" :src="currentRow.idCardFront" style="width:120px;height:120px;" fit="contain" />
            <div v-else style="width:120px;height:120px;background:#fafbfc;border:1px solid #eee;"></div>
          </el-col>
          <el-col :span="6">
            <el-image v-if="currentRow.idCardBack" :src="currentRow.idCardBack" style="width:120px;height:120px;" fit="contain" />
            <div v-else style="width:120px;height:120px;background:#fafbfc;border:1px solid #eee;"></div>
          </el-col>
        </el-row>
        <div style="margin-top:24px; text-align:right;">
          <el-button @click="openCancelDialog">审核作废</el-button>
          <el-button type="danger" @click="openApproveDialog">审核通过</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 作废原因弹窗 -->
    <el-dialog v-model="cancelDialogVisible" title="作废原因" width="500px" :close-on-click-modal="false">
      <div style="margin-bottom:16px;display:flex;gap:12px;">
        <el-button
          v-for="item in cancelReasonOptions"
          :key="item"
          :type="selectedCancelReason === item ? 'primary' : 'default'"
          @click="selectCancelReason(item)"
          plain
        >
          {{ item }}
        </el-button>
      </div>
      <el-input
        v-model="cancelReason"
        placeholder="请手动输入原因"
        maxlength="50"
        show-word-limit
      />
      <div style="margin-top:32px;text-align:right;">
        <el-button @click="cancelDialogVisible=false">取消</el-button>
        <el-button type="danger" @click="submitCancelReason">确定</el-button>
      </div>
    </el-dialog>
    <!-- 审核通过确认弹窗 -->
    <el-dialog v-model="approveDialogVisible" title="提示" width="400px" :close-on-click-modal="false">
      <div style="margin: 24px 0 32px 0; font-size: 16px;">
        确定要通过
        <span style="color: #f00; font-weight: bold;">{{ currentRow?.name }}</span>
        的团长申请吗？
      </div>
      <div style="text-align:right;">
        <el-button @click="approveDialogVisible=false">取消</el-button>
        <el-button type="danger" @click="submitApprove">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单数据
const searchForm = ref({
  name: '',
  phone: '',
  storeName: '',
  address: '',
  storeType: '' // 默认全部
})

// 自提点类型选项
const storeTypeOptions = [
  { label: '全部', value: '' },
  { label: '便利店', value: '便利店' },
  { label: '快递点', value: '快递点' }
];

// 表格数据类型定义
interface LeaderAuditRecord {
  id: string
  applyTime: string
  name: string
  phone: string
  storeName: string
  address: string
  storeType: string
  // 新增字段
  wxInfo?: string
  hasStore?: boolean
  coordinate?: string
  doorNumber?: string
  openTime?: string
  closeTime?: string
  licenseImg?: string
  storeImg?: string
  backupPhone?: string
  idCardFront?: string
  idCardBack?: string
}

const allData: LeaderAuditRecord[] = [
  {
    id: '202002200001',
    applyTime: '2020-02-14 14:30:30',
    name: '张三',
    phone: '18555555551',
    backupPhone: '18555555561',
    storeName: '菜鸟驿站',
    address: '北京市石景山区',
    storeType: '便利店',
    wxInfo: 'wx_zhangsan',
    hasStore: true,
    coordinate: '23811331.22; 231332344.31',
    doorNumber: '1-101',
    openTime: '8:00',
    closeTime: '22:00',
    licenseImg: '',
    storeImg: '',
    idCardFront: '',
    idCardBack: ''
  },
  {
    id: '202002200002',
    applyTime: '2020-02-15 09:15:20',
    name: '李四',
    phone: '18555555552',
    backupPhone: '18555555562',
    storeName: '全家便利店',
    address: '北京市海淀区',
    storeType: '便利店',
    wxInfo: 'wx_lisi',
    hasStore: false,
    coordinate: '23811332.22; 231332345.31',
    doorNumber: '2-202',
    openTime: '9:00',
    closeTime: '21:00',
    licenseImg: '',
    storeImg: '',
    idCardFront: '',
    idCardBack: ''
  },
  {
    id: '202002200003',
    applyTime: '2020-02-15 16:45:10',
    name: '王五',
    phone: '18555555553',
    backupPhone: '18555555563',
    storeName: '京东派',
    address: '北京市朝阳区',
    storeType: '快递点',
    wxInfo: 'wx_wangwu',
    hasStore: true,
    coordinate: '23811333.22; 231332346.31',
    doorNumber: '3-303',
    openTime: '7:30',
    closeTime: '20:00',
    licenseImg: '',
    storeImg: '',
    idCardFront: '',
    idCardBack: ''
  },
  {
    id: '202002200004',
    applyTime: '2020-02-16 10:20:15',
    name: '赵六',
    phone: '18555555554',
    backupPhone: '18555555564',
    storeName: '7-11便利店',
    address: '北京市西城区',
    storeType: '便利店',
    wxInfo: 'wx_zhaoliu',
    hasStore: false,
    coordinate: '23811334.22; 231332347.31',
    doorNumber: '4-404',
    openTime: '10:00',
    closeTime: '23:00',
    licenseImg: '',
    storeImg: '',
    idCardFront: '',
    idCardBack: ''
  },
  {
    id: '202002200005',
    applyTime: '2020-02-16 11:30:25',
    name: '钱七',
    phone: '18555555555',
    backupPhone: '18555555565',
    storeName: '顺丰快递点',
    address: '北京市东城区',
    storeType: '快递点',
    wxInfo: 'wx_qianqi',
    hasStore: true,
    coordinate: '23811335.22; 231332348.31',
    doorNumber: '5-505',
    openTime: '8:30',
    closeTime: '19:30',
    licenseImg: '',
    storeImg: '',
    idCardFront: '',
    idCardBack: ''
  },
  {
    id: '202002200006',
    applyTime: '2020-02-16 14:20:35',
    name: '孙八',
    phone: '18555555556',
    backupPhone: '18555555566',
    storeName: '罗森便利店',
    address: '北京市丰台区',
    storeType: '便利店',
    wxInfo: 'wx_sunba',
    hasStore: false,
    coordinate: '23811336.22; 231332349.31',
    doorNumber: '6-606',
    openTime: '6:00',
    closeTime: '18:00',
    licenseImg: '',
    storeImg: '',
    idCardFront: '',
    idCardBack: ''
  },
  {
    id: '202002200007',
    applyTime: '2020-02-16 16:15:40',
    name: '周九',
    phone: '18555555557',
    backupPhone: '18555555567',
    storeName: '百世快递',
    address: '北京市通州区',
    storeType: '快递点',
    wxInfo: 'wx_zhoujiu',
    hasStore: true,
    coordinate: '23811337.22; 231332350.31',
    doorNumber: '7-707',
    openTime: '8:00',
    closeTime: '22:00',
    licenseImg: '',
    storeImg: '',
    idCardFront: '',
    idCardBack: ''
  },
  {
    id: '202002200008',
    applyTime: '2020-02-17 09:10:50',
    name: '吴十',
    phone: '18555555558',
    backupPhone: '18555555568',
    storeName: '良品铺子',
    address: '北京市大兴区',
    storeType: '便利店',
    wxInfo: 'wx_wushi',
    hasStore: false,
    coordinate: '23811338.22; 231332351.31',
    doorNumber: '8-808',
    openTime: '9:30',
    closeTime: '21:30',
    licenseImg: '',
    storeImg: '',
    idCardFront: '',
    idCardBack: ''
  },
  {
    id: '202002200009',
    applyTime: '2020-02-17 10:30:00',
    name: '郑十一',
    phone: '18555555559',
    backupPhone: '18555555569',
    storeName: '苏宁小店',
    address: '北京市昌平区',
    storeType: '便利店',
    wxInfo: 'wx_zhengshiyi',
    hasStore: true,
    coordinate: '23811339.22; 231332352.31',
    doorNumber: '9-909',
    openTime: '7:00',
    closeTime: '19:00',
    licenseImg: '',
    storeImg: '',
    idCardFront: '',
    idCardBack: ''
  },
  {
    id: '202002200010',
    applyTime: '2020-02-17 11:45:15',
    name: '钱十二',
    phone: '18555555560',
    backupPhone: '18555555570',
    storeName: '天虹超市',
    address: '北京市房山区',
    storeType: '便利店',
    wxInfo: 'wx_qianshier',
    hasStore: false,
    coordinate: '23811340.22; 231332353.31',
    doorNumber: '10-1010',
    openTime: '10:00',
    closeTime: '20:00',
    licenseImg: '',
    storeImg: '',
    idCardFront: '',
    idCardBack: ''
  }
];

// 表格数据
const tableData = ref<LeaderAuditRecord[]>([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(2); // 默认显示2条
const total = ref(allData.length);

// 加载状态
const loading = ref(false)

// 当前激活的标签页
const activeTab = ref('pending')

// 选中的行
const selectedRows = ref<LeaderAuditRecord[]>([])

// 弹窗相关
const dialogVisible = ref(false)
const currentRow = ref<LeaderAuditRecord | null>(null)

// 作废原因弹窗相关
const cancelDialogVisible = ref(false)
const cancelReason = ref('')
const cancelReasonOptions = ['用户主动要求', '信息填写错误', '恶意注册']
const selectedCancelReason = ref('')

function openCancelDialog() {
  cancelDialogVisible.value = true
  cancelReason.value = ''
  selectedCancelReason.value = ''
}
function selectCancelReason(item: string) {
  selectedCancelReason.value = item
  cancelReason.value = item
}
function submitCancelReason() {
  if (!cancelReason.value) {
    ElMessage.warning('请输入作废原因')
    return
  }
  // TODO: 可在此处提交作废原因
  ElMessage.success('作废原因已提交: ' + cancelReason.value)
  cancelDialogVisible.value = false
  dialogVisible.value = false
}

// 审核通过弹窗相关
const approveDialogVisible = ref(false)
function openApproveDialog() {
  approveDialogVisible.value = true
}
function submitApprove() {
  if (!currentRow.value) return;
  const name = currentRow.value.name;
  // 1. 取出localStorage已通过列表
  const passedList = JSON.parse(localStorage.getItem('leaderManagementList') || '[]');
  // 2. 添加当前数据
  passedList.push({ ...currentRow.value });
  // 3. 存回localStorage
  localStorage.setItem('leaderManagementList', JSON.stringify(passedList));
  // 4. 移除本地数据并刷新表格
  const idx = allData.findIndex(item => item.id === currentRow.value?.id)
  if (idx !== -1) allData.splice(idx, 1)
  updateTableData()
  ElMessage.success('已通过 ' + name + ' 的团长申请')
  approveDialogVisible.value = false
  dialogVisible.value = false
}

// 处理选择变化
const handleSelectionChange = (rows: LeaderAuditRecord[]) => {
  selectedRows.value = rows
}

// 更新表格数据
const updateTableData = () => {
  // 先根据筛选条件过滤数据
  let filteredData = [...allData];
  
  // 按搜索条件筛选
  filteredData = filteredData.filter(item => {
    // 姓名模糊匹配
    const nameMatch = !searchForm.value.name || 
      item.name.toLowerCase().includes(searchForm.value.name.toLowerCase());
    
    // 手机号模糊匹配
    const phoneMatch = !searchForm.value.phone || 
      item.phone.includes(searchForm.value.phone);
    
    // 自提点名称模糊匹配
    const storeNameMatch = !searchForm.value.storeName || 
      item.storeName.toLowerCase().includes(searchForm.value.storeName.toLowerCase());
    
    // 地址模糊匹配
    const addressMatch = !searchForm.value.address || 
      item.address.toLowerCase().includes(searchForm.value.address.toLowerCase());
    
    // 自提点类型精确匹配
    const storeTypeMatch = !searchForm.value.storeType || 
      item.storeType === searchForm.value.storeType;
    
    return nameMatch && phoneMatch && storeNameMatch && addressMatch && storeTypeMatch;
  });

  // 更新总数
  total.value = filteredData.length;

  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  tableData.value = filteredData.slice(start, end);
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  updateTableData();
};

// 重置
const handleReset = () => {
  searchForm.value = {
    name: '',
    phone: '',
    storeName: '',
    address: '',
    storeType: ''
  };
  currentPage.value = 1; // 重置到第一页
  updateTableData();
};

// 批量通过
const handleBatchApprove = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要通过的记录')
    return
  }
  ElMessageBox.confirm('确定要通过选中的记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // TODO: 实现批量通过逻辑
    ElMessage.success('操作成功')
  })
}

// 批量作废
const handleBatchReject = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要作废的记录')
    return
  }
  ElMessageBox.confirm('确定要作废选中的记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // TODO: 实现批量作废逻辑
    ElMessage.success('操作成功')
  })
}

// 查看详情
const handleView = (row: LeaderAuditRecord) => {
  currentRow.value = row
  dialogVisible.value = true
}

// 通过
const handleApprove = (row: any) => {
  ElMessageBox.confirm('确定要通过该记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // TODO: 实现通过逻辑
    ElMessage.success('操作成功')
  })
}

// 作废
const handleReject = (row: any) => {
  ElMessageBox.confirm('确定要作废该记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // TODO: 实现作废逻辑
    ElMessage.success('操作成功')
  })
}

// 监听自提点类型变化
watch(() => searchForm.value.storeType, (newVal) => {
  currentPage.value = 1; // 重置到第一页
  updateTableData();
});

// 处理每页显示数量变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
  updateTableData();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  updateTableData();
};

onMounted(() => {
  updateTableData(); // 初始化表格数据
});
</script>

<style scoped>
.leader-audit {
  padding: 20px;
}

.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.button-group {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.pagination-info {
  color: #999;
  font-size: 16px;
  margin-left: 16px;
}

:deep(.el-pagination) {
  .el-pagination__total {
    display: none !important;
  }

  .el-pager li {
    margin: 0 4px;
    min-width: 32px;
    border-radius: 4px;
    
    &.is-active {
      background-color: #ff0000;
      color: white;
    }
  }

  .btn-prev,
  .btn-next {
    margin: 0 4px;
    min-width: 32px;
    border-radius: 4px;
    background-color: #f4f4f5;
  }

  .el-pagination__sizes {
    margin-right: 0;
  }
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
}

:deep(.el-select) {
  .el-input__wrapper {
    padding-right: 25px !important;
  }
  .el-input__inner {
    text-align: right;
  }
}
</style> 